import datetime

from coin.exchange.base.kr_rest.derivative_util import (PERPETUAL_DATE)
from coin.exchange.bitmex.kr_rest.constants import contract_type_list
import coin.exchange.bitmex.kr_rest.exp_util as exp_util


def find_contract_type_from_expiry(current_datetime, expiry):
  if expiry == PERPETUAL_DATE:
    return 'perpetual'

  expiry = exp_util.expiry_accurate_datetime(expiry)
  quarter_expiry = exp_util.expiry_accurate_datetime(
      datetime.datetime.strptime(exp_util.find_quarter_contract_expiring_date(current_datetime),
                                 "%Y%m%d"))
  next_quarter_expiry = exp_util.expiry_accurate_datetime(
      datetime.datetime.strptime(
          exp_util.find_next_quarter_contract_expiring_date(current_datetime), "%Y%m%d"))

  if expiry == quarter_expiry:
    return 'quarter'
  elif expiry == next_quarter_expiry:
    return 'next_quarter'
  else:
    raise ValueError(current_datetime, expiry)


def find_expiry_from_contract_type(current_datetime, contract_type):
  if contract_type == 'perpetual':
    return PERPETUAL_DATE

  assert contract_type in contract_type_list
  if contract_type == 'quarter':
    return exp_util.find_quarter_contract_expiring_date(current_datetime)
  elif contract_type == 'next_quarter':
    return exp_util.find_next_quarter_contract_expiring_date(current_datetime)
  else:
    raise ValueError(current_datetime, contract_type)


def to_expiry_str_contract_type(expiry_str, current_datetime):
  if expiry_str == 'perpetual':
    contract_type = 'perpetual'
  elif expiry_str in contract_type_list:
    contract_type = expiry_str
    expiry_str = find_expiry_from_contract_type(current_datetime, contract_type)
  elif expiry_str.isdigit():
    expiry = datetime.datetime.strptime(expiry_str, '%Y%m%d')
    contract_type = find_contract_type_from_expiry(current_datetime, expiry)
    expiry_str = expiry.strftime("%Y%m%d")
  else:
    raise ValueError(product)
  return expiry_str, contract_type
